# -*- coding:UTF-8 -*-
from cmdb.models import ApplyBusinessLog
from django.db.models import Q

def apply_business_log(search,status,start,end):
    count = 0
    aRes = {}
    if search == '':
        if status == 100:
            count=ApplyBusinessLog.objects.count()
            aRes = ApplyBusinessLog.objects.order_by('-id')[start:end]
        else:
            count=ApplyBusinessLog.objects.filter(status=status).count()
            aRes = ApplyBusinessLog.objects.filter(status=status).order_by('-id')[start:end]
    else:
        if status == 100:
            count=ApplyBusinessLog.objects.filter(applier__icontains=search).count()
            aRes = ApplyBusinessLog.objects.filter(applier__icontains=search).order_by('-id')[start:end]
        else:
            count=ApplyBusinessLog.objects.filter(Q(status=status),Q(applier__icontains=search)).count()
            aRes = ApplyBusinessLog.objects.filter(Q(status=status),Q(applier__icontains=search)).order_by('-id')[start:end]
    return {'count':count,'apply_business_log_list':aRes}

def get_apply_business_log(id):
    applyRes = ApplyBusinessLog.objects.get(id=id)
    return applyRes

def update_status_apply_log(id, status, cursor):
    apply_log_update_sql = "update apply_business_log set status=" + status + " where id=" + id
    cursor.execute(apply_log_update_sql)

def add_apply_business_log(applier, depart_manger, category, parent_category, module_name,module_number,
                           apply_server_number, status, description):
    applyInfo = ApplyBusinessLog(applier=applier,depart_manger=depart_manger,category=category,parent_category=parent_category,
                    module_name=module_name,module_number=module_number,apply_server_number=apply_server_number,
                    status=status,description=description)
    applyInfo.save()

def exist_apply_business_log(category, module_name):
    count = ApplyBusinessLog.objects.filter(Q(category=category),Q(module_name=module_name)).count()
    if count > 0:
        return True
    return False
